
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-04
 * Time: 23:11
 */
class MyBlockingQueue{
    private int head = 0;
    private int tail = 0;
    private int useSize = 0;
    private final String[] array;

    public MyBlockingQueue(int capacity){
        array = new String[capacity];
    }
    //添加
    public synchronized void put(String string) throws InterruptedException {
        if (isFull()){
            //队列满了,等待消费者消耗元素
            this.wait();
        }
        array[tail] = string;
        tail++;
        tail = (tail + 1) % array.length;
        useSize++;
        this.notify();
    }
    //删除
    public String take() throws InterruptedException {
        String ret;
        synchronized (this) {
            if (useSize <= 0) {
                //队列空了,等待生产者添加元素.
                this.wait();
            }
            ret = array[head];
            head++;
            head = (head + 1) % array.length;
            useSize--;
            this.notify();
        }
        return ret;
    }
    //判断是否满了
    public boolean isFull(){
        return useSize >= array.length;
    }
}

public class Main {
    public static void main(String[] args){
        MyBlockingQueue queue = new MyBlockingQueue(100);
        Thread thread1 = new Thread(()->{
            int n = 1;
            while (true){
                try {
                    queue.put(n + "");
                    System.out.println("生产元素 " + n);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        Thread thread2 = new Thread(()->{
            while (true){
                try {
                    String s = queue.take();
                    System.out.println("消费元素 " + s);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}